define(['./../initial', './../model/ProjectMap', './symbolFactory', './renderPointsOnMap', './zoomMap'], function() {
    var app = angular.module('App.home');
    app.factory('loadProjectMap', ['ProjectMap', '$q', 'symbolFactory', 'mapInstance', 'renderPointsOnMap', '$timeout', 'zoomMap', 'toggleSideBar', '$rootScope',
        function(ProjectMap, $q, symbolFactory, mapInstance, renderPointsOnMap, $timeout, zoomMap, toggleSideBar, $rootScope) {
            return function(prj, paras) {
                var option = {
                    autoSurvey: false, //是否进入自动化测量模式
                    autoSurveyPrjName: ''
                };

                //关闭filterProject
                $rootScope.$broadcast('filterProjectClick', false);

                option = $.extend(option, paras);
                var deferred = $q.defer();
                var curPoints = null;

                var map = mapInstance.getMap();
                if (map.viewState === 'active') {
                    map.clearPointsLayer();
                    map.toggleAutoSurvey(option.autoSurvey, option.autoSurveyPrjName);
                    deferred.resolve();
                    return deferred.promise;
                } else {
                    map.remove();
                    map = new ProjectMap('map', {
                        crs: L.CRS.Simple,
                        zoom: 1,
                        zoomControl: false,
                        maxZoom: 3,
                        doubleClickZoom: false,
                        autoSurveyMode: option.autoSurvey,
                        autoSurveyPrjName: option.autoSurveyPrjName
                    });
                    map.attributionControl.setPrefix('<a href="/">' + prj.name + '</a>');
                    mapInstance.setMap(map, 'active');

                    var zoomMarkers = function(currentZoom) {
                        var className = "map-zoom-" + currentZoom.toString();
                        var maxZoom = map.getMaxZoom();
                        var i = 0;
                        while (i <= maxZoom) {
                            if (i !== currentZoom) {
                                $(".point-marker").removeClass('map-zoom-' + i.toString());
                            }
                            i++;
                        }
                        $(".point-marker").addClass(className);
                    };
                    var addPointsTxt = function(currentZoom) {
                        var maxZoom = map.getMaxZoom();
                        if (!curPoints) return;
                        var mlayer = map.curPointTxtLayer;
                        if (currentZoom !== maxZoom) {
                            // mlayer.clearLayers();
                        } else {
                            var txtXoffset = map.unproject([0, 20], maxZoom).lat;
                            curPoints.forEach(function(pt) {
                                var labelIcon = L.divIcon({
                                    'html': '<span>' + pt.name + '</span>',
                                    'className': 'point-marker-txt',
                                    'iconSize': {
                                        x: 10,
                                        y: 10
                                    }
                                });
                                var marker = L.marker([pt.geometry[1] - txtXoffset, pt.geometry[0]], {
                                    icon: labelIcon
                                });
                                mlayer.addLayer(marker);
                            });
                        }
                    };

                    map.on('finishLoadingLayers', function() {
                        document.getElementById("progressBar").style.width = "100%";
                        $('#progressBar').removeClass('progressBar');
                        document.getElementById("progress").style.visibility = "hidden";
                    });
                    map.on('startLoadingLayers', function() {

                    });


                    //begin loading layers on map
                    $('#progressBar').addClass('progressBar');
                    document.getElementById("progress").style.visibility = "visible";
                    prj.getProjectLayers().then(function() {
                        return zoomMap(prj.projectMapCenter, 1);
                    }).then(function() {
                        //start loading
                        return map.loadProjectLayers(prj.layers);
                        //finish loading
                    }).then(function() {
                        if (!map.autoSurveyMode) {
                            return renderPointsOnMap();
                        }
                    }).then(function(pts) { //当前点加载完成以后
                        map.addEventListener('renderPointsRequired', function(event) {
                            //当需要重新加载其他点的时候,取消自动化
                            map.toggleAutoSurvey(false); //取消自动化
                            renderPointsOnMap().then(function(targetPoints) {
                                curPoints = targetPoints;
                            });
                        });
                        curPoints = pts || null; // 重新定义curPoints
                        map.on('zoomend', function(event) {
                            if (map.autoSurveyMode) return;
                            var currentZoom = map.getZoom();
                            zoomMarkers(currentZoom);
                            addPointsTxt(currentZoom);
                        });
                        map.on('zoomstart', function(event) {
                            if (map.autoSurveyMode) return;
                            map.curPointTxtLayer.clearLayers();
                        });
                        //注册marker的hover事件
                        map.addEventListener('makerHoverActive', function(event) {
                            if (map.autoSurveyMode) return;
                            var name = event.ptName;
                            map.curPtNameHoverTime = Date.now();
                            var layers = map.curPointMarksLayer.getLayers();
                            var marker = null;
                            for (var i = 0; i < layers.length; i++) {
                                if (layers[i].name === name) {
                                    marker = layers[i];
                                    break;
                                }
                            }
                            if (!marker) return;
                            var pos = marker.getLatLng();
                            var offset = map.unproject([0, 200], map.getZoom());
                            $timeout((function(name, pos, offset) {
                                return function() {
                                    var time = Date.now() - map.curPtNameHoverTime;
                                    if (time >= 800) { //用户鼠标停留800ms以上才打开popup
                                        zoomMap([pos.lat + offset.lat, pos.lng]).then(function() {
                                            $('#' + name).parent().addClass('point-marker-active');
                                        });
                                    }
                                };
                            })(name, pos, offset), 800);

                        });
                        map.addEventListener('makerHoverInactive', function(event) {
                            if (map.autoSurveyMode) return;
                            var name = event.ptName;
                            map.curPtNameHoverTime = Date.now();
                            $timeout(function() {
                                $('#' + name).parent().removeClass('point-marker-active');
                            }, 100);
                        });
                        map.on('click', function(event) {
                            if (map.autoSurveyMode) return;
                            toggleSideBar.toggleBottomSideBar();
                        });
                        deferred.resolve();
                    });
                    return deferred.promise;
                }
            };
        }
    ]);
});
